package com.hxzy.controller.system;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hxzy.common.annotation.Log;
import com.hxzy.common.core.controller.BaseController;
import com.hxzy.common.core.domain.R;
import com.hxzy.common.core.domain.entity.SysRole;
import com.hxzy.common.core.domain.entity.SysUser;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.enums.BusinessType;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.utils.poi.ExcelUtil;
import com.hxzy.common.validator.AddValidator;
import com.hxzy.common.validator.EditValidator;
import com.hxzy.system.domain.SysPost;
import com.hxzy.system.domain.dto.SysUserSearchDTO;
import com.hxzy.system.service.ISysPostService;
import com.hxzy.system.service.ISysRoleService;
import com.hxzy.system.service.ISysUserService;
import com.mysql.cj.exceptions.PasswordExpiredException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理
 *
 * @Author： 17602
 * @Date： 2022/9/5 21:34
 * @Desc： 用户管理
 **/
@Api(tags = "用户管理")
@RequestMapping("/api/system/user")
@RestController
public class SysUserController extends BaseController {

    @Autowired
    ISysUserService userService;

    @Autowired
    ISysRoleService roleService;

    @Autowired
    ISysPostService postService;

    @ApiOperation(value = "分页获取用户信息")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @GetMapping("/list")
    public R list(SysUserSearchDTO sysUserSearchDTO) {
        IPage<SysUser> page = this.userService.selectUserList(sysUserSearchDTO);
        return super.pageVO(page);
    }

    @ApiModelProperty("更换用户状态")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody @Validated(value = EditValidator.class) SysUser sysUser) {
        if (ObjectUtil.isNull(sysUser) || this.roleService.isAdmin(sysUser.getUserId())) {
            throw new ServiceException("不允许操作该用户");
        }

        int changeStatus = this.userService.changeStatus(sysUser);
        return changeStatus >= 0 ? R.ok() : R.build(AckCode.FAIL);
    }

    @ApiOperation(value = "重置密码")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody @Validated(value = EditValidator.class) SysUser sysUser) {
        if (ObjectUtil.isNull(sysUser) || ObjectUtil.isNull(sysUser.getUserId()) || StrUtil.isBlank(sysUser.getPassword())) {
            throw new PasswordExpiredException("无效重置密码操作！");
        }
        int restResult = this.userService.restPwd(sysUser);
        return restResult >= 0 ? R.ok() : R.build(AckCode.FAIL);
    }

    @ApiOperation(value = "获取某个用户的信息")
    @Log(title = "用户管理", businessType = BusinessType.OTHER)
    @GetMapping("/{id}")
    public R getUserById(@PathVariable Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new ServiceException(AckCode.USER_NOT_FOUND.msg);
        }
        SysUser sysUser = this.userService.selectUserById(id);
        // 岗位id+岗位列表 + 角色id+角色列表
        List<SysPost> allPost = this.postService.selectPostAll();
        List<SysRole> allRole;

        // 管理员全角色 其他只有普通角色
        if (this.roleService.isAdmin(id)) {
            allRole = this.roleService.selectRoleAll();
        } else {
            allRole = this.roleService.selectNormalRoles();
        }

        List<SysPost> postList = this.postService.selectPostByUserId(id);
        List<SysRole> roleList = this.roleService.selectRolesByUserId(id);
        System.out.println("postList = " + postList);
        System.out.println("roleList = " + roleList);

        List<Long> postIds = null;
        if (CollectionUtil.isNotEmpty(roleList)) {
            postIds = postList.stream().map(SysPost::getPostId).collect(Collectors.toList());
        }
        List<Long> roleIds = null;
        if (CollectionUtil.isNotEmpty(roleList)) {
            roleIds = roleList.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("posts", allPost);
        map.put("postIds", postIds);
        map.put("roles", allRole);
        map.put("roleIds", roleIds);
        map.put("user", sysUser);
        return R.okHasData(map);
    }

    @ApiOperation(value = "移除某个用户的信息")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R removeUserById(@PathVariable Long[] ids) {
        for (Long id : ids) {
            if (ObjectUtil.isNull(id) || this.roleService.isAdmin(id)) {
                throw new ServiceException("不允许操作该用户");
            }
            SysUser sysUser = this.userService.selectUserById(id);
            if (ObjectUtil.isNotNull(sysUser)) {
                sysUser.setDelFlag("2");
                this.userService.updateUserByUserId(sysUser);
            }

        }
        return R.ok();
    }

    @ApiOperation(value = "获取用户授权数据")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @GetMapping("/authRole/{id}")
    public R authRole(@PathVariable Long id) {
        if (ObjectUtil.isNull(id) || this.roleService.isAdmin(id)) {
            throw new ServiceException("不允许操作该用户");
        }
        SysUser user = userService.selectUserById(id);
        List<SysRole> roles = roleService.selectNormalRoles();

        HashMap<Object, Object> map = new HashMap<>(2);
        map.put("user", user);
        map.put("roles", roles);

        return R.okHasData(map);
    }

    @ApiOperation(value = "给用户授权")
    @PutMapping("/authRole")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    public R authRole(Long userId, Long[] roleIds) {
        if (ObjectUtil.isNull(userId) || this.roleService.isAdmin(userId)) {
            throw new ServiceException("不允许操作该用户");
        }

        this.roleService.grantRolesForUser(userId, roleIds);
        return R.ok();
    }

    @GetMapping("/")
    @ApiOperation(value = "获取岗位列表+角色列表")
    @Log(title = "用户管理", businessType = BusinessType.OTHER)
    public R getPotsAndRole() {
        List<SysPost> postList = this.postService.selectPostAll();
        List<SysRole> roleList = this.roleService.selectNormalRoles();

        HashMap<String, Object> map = new HashMap<>();
        map.put("posts", postList);
        map.put("roles", roleList);
        return R.okHasData(map);
    }

    @Transactional
    @PostMapping("/add")
    @ApiOperation(value = "添加用户")
    public R addUser(@RequestBody @Validated(value = AddValidator.class) SysUser sysUser) {
        int insert = userService.insertSysUser(sysUser);
//        if (insert > 0) {
//            Long[] roleIds = sysUser.getRoleIds();
//            Long[] postIds = sysUser.getPostIds();
//
//            // 授予角色
//            if (roleIds.length > 0) {
//                this.roleService.grantRolesForUser(sysUser.getUserId(), roleIds);
//            }
//
//            // 授予岗位
//            if (postIds.length > 0) {
//                this.postService.grantPostForUser(sysUser.getUserId(), Arrays.asList(postIds));
//            }
//        }
        return insert > 0 ? R.ok() : R.build(AckCode.FAIL);
    }

    @Transactional
    @PutMapping("")
    @ApiOperation(value = "修改用户")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public R editUser(@RequestBody @Validated(value = EditValidator.class) SysUser sysUser) {
        int insert = userService.updateUserByUserId(sysUser);
        return insert > 0 ? R.ok() : R.build(AckCode.FAIL);
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }


    @PostMapping("/export")
    @ApiOperation(value = "用户信息导出")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    public void expireUser(HttpServletResponse response, SysUserSearchDTO sysUserSearchDTO) {
        IPage<SysUser> page = userService.selectUserList(sysUserSearchDTO);
        ExcelUtil<SysUser> excelUtil = new ExcelUtil<>(SysUser.class);
        excelUtil.exportExcel(response, page.getRecords(), "员工信息");
    }
}
